package chatroom

import (
	"context"
	"fmt"

	"go-admin/base/internal/svc"
	"go-admin/base/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type MessagesLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewMessagesLogic(ctx context.Context, svcCtx *svc.ServiceContext) *MessagesLogic {
	return &MessagesLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *MessagesLogic) Messages(req *types.MessageReqDTO) (resp *types.MessageRespDTOS, err error) {
	var fromToId string
	if req.FromID < req.ToID {
		fromToId = fmt.Sprintf("%d:%d", req.FromID, req.ToID)
	} else {
		fromToId = fmt.Sprintf("%d:%d", req.ToID, req.FromID)
	}
	messages, err := l.svcCtx.MessageModel.FindManyByFromToId(l.ctx, fromToId)
	if err != nil {
		_ = fmt.Errorf(err.Error())
		return nil, err
	}
	var messageRespDTOs []types.MessageRespDTO
	for _, message := range messages {
		messageRespDTOs = append(messageRespDTOs, types.MessageRespDTO{
			FromID:   message.FromID,
			ToID:     message.ToID,
			FromName: message.FromName,
			ToName:   message.ToName,
			FromToID: message.FromToID,
			Type:     message.Type,
			ID:       message.ID.String(),
			Content:  message.Content,
			CreateAt: message.CreateAt.Unix(),
			UpdateAt: message.UpdateAt.Unix(),
		})
	}

	return &types.MessageRespDTOS{
		Data: messageRespDTOs,
		Result: types.Result{
			Code: 200,
		},
	}, nil
}
